package org.example.cdpcrpbackend.controller;

import cn.hutool.crypto.SecureUtil;
import lombok.RequiredArgsConstructor;
import org.example.cdpcrpbackend.controller.dto.LoginRequest;
import org.example.cdpcrpbackend.controller.dto.Result;
import org.example.cdpcrpbackend.controller.dto.StudentInfo;
import org.example.cdpcrpbackend.domain.Student;
import org.example.cdpcrpbackend.service.StudentService;
import org.example.cdpcrpbackend.util.JwtTool;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/student")
@RequiredArgsConstructor
public class StudentController {
    private final StudentService service;

    /**
     * 小程序-登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest body) {
        String md5Password = SecureUtil.md5(body.getPassword());
        Student student = service.login(body.getUsername(), md5Password);
        if (student == null) {
            return Result.fail("登录失败");
        } else {
            String studentId = student.getId();
            StudentInfo info = service.studentInfo(studentId);
            info.setToken(JwtTool.createToken(studentId));
            return Result.success(info);
        }
    }

    /**
     * 获取学生信息
     *
     * @param id 学号
     */
    @RequestMapping("/info/{id}")
    public Result info(@PathVariable("id") String id) {
        return Result.success(service.studentInfo(id));
    }

    /**
     * 修改学生信息头像和邮箱
     *
     * @param student 学生数据
     */
    @PostMapping("/update")
    public Result update(@RequestBody Student student) {
        // 通过学号查询
        Student dbStu = service.getById(student.getId());
        if (dbStu == null) {
            return Result.fail("学生不存在");
        }
        // 修改头像和邮箱
        dbStu.setAvatar(student.getAvatar());
        dbStu.setEmail(student.getEmail());
        service.updateById(dbStu);
        return Result.success();
    }

    // 修改密码
//    @PostMapping("/updatePassword")
//    public Result updatePassword(@RequestBody StudentUpdatePassword student) {
//        // 通过学号查询
//        Student dbStu = service.getById(student.getId());
//        if (dbStu == null) {
//            return Result.fail("学生不存在");
//        }
//        // 修改密码
//        dbStu.setPassword(student.getPassword());
//        service.updateById(dbStu);
//        return Result.success();
//    }
}
